package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * app端用户登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult apUserLogin(LoginDto loginDto) {
        HashMap<String, Object> map = new HashMap<>();
        //1.非空判断，不为空则用户登录
        if (StringUtils.isNotEmpty(loginDto.getPhone()) && StringUtils.isNotEmpty(loginDto.getPassword())) {
            //1.1根据手机号去数据库找
            ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            //1.2判断数据库里是否有,没有，则返回异常
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
            //1.3有，则对参数密码加盐加密
            String pwd = DigestUtils.md5DigestAsHex((loginDto.getPassword() + apUser.getSalt()).getBytes());

            //1.4对比相对应的数据库手机的密码，不对，则报错
            if (!apUser.getPassword().equals(pwd)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.5把data数据与token存入map，并返回
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("user", apUser);
            map.put("Token", AppJwtUtil.getToken(Long.valueOf(apUser.getId())));
            //1.6重要数据不返回
            return ResponseResult.okResult(map);
        } else {
            //2.空，则游客登录
            map.put("Token", AppJwtUtil.getToken(0L));
            //2.1设置data为零,并返回map
            return ResponseResult.okResult(map);
        }


    }
}
